package validation

import (
	"fmt"
	"github.com/go-playground/validator/v10"
	"reflect"
)

type ValidatorMessages = map[string]string

type IValidator interface {
	GetMessage() ValidatorMessages
	TranslateMessage() ValidatorMessages
}

/**
 * 错误信息和统一返回
 * @author feige
 * @date 2024-04-17
 * @version 1.0
 * @desc
 */
func GetErrorMesssages(err error, request IValidator) ValidatorMessages {
	validatorMessages := ValidatorMessages{}
	if fieldErrors, ok := err.(validator.ValidationErrors); ok {
		for _, fieldError := range fieldErrors {
			messages := request.GetMessage()
			errorMsg := messages[fieldError.Field()+"."+fieldError.Tag()]
			if len(errorMsg) == 0 {
				s := reflect.TypeOf(request).Elem()
				field, _ := s.FieldByName(fieldError.StructField())
				label := field.Tag.Get("label")
				if len(label) == 0 {
					labelMessages := request.TranslateMessage()
					label = labelMessages[fieldError.Field()]
				}
				errorMsg = fmt.Sprintf(messages[fieldError.Tag()], label)
			}
			validatorMessages[fieldError.Field()] = errorMsg
		}
	}
	return validatorMessages
}
